package com.tao.service.impl;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.tao.service.EmailService;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Service
public class EmailServiceImpl implements EmailService{
	
	private static final Log logger = LogFactory.getLog(EmailServiceImpl.class);
	
	@Autowired
	private JavaMailSender javaMailSender;
	
	@Autowired
	FreeMarkerConfigurer freeMarkerConfigurer;

	@Override
	public void SendMail(String subject, String fromEmail, String[] recipients,
			String templateID, Map<String, Object> paraMap) {
		
		logger.info("====================[templateID]"+templateID);
		
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		configuration.setClassForTemplateLoading(this.getClass(), "/");
		try {
			Template t = configuration.getTemplate("email/"+templateID);
			String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, paraMap);
			System.out.println(content);
			MimeMessage msg = javaMailSender.createMimeMessage();
	        MimeMessageHelper helper  =  new  MimeMessageHelper(msg);
	        helper.setFrom(fromEmail);  
	        helper.setTo(recipients);  
	        helper.setSubject(subject);  
	        helper.setText(content,true);
	        javaMailSender.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void SendMail(String subject, String[] recipients,
			Map<String, String> ccs, String templateID,
			Map<String, Object> rootMap) {
		// TODO Auto-generated method stub
		
	}



}
